package com.zdf.license.core.service;

import lombok.extern.log4j.Log4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.stream.Stream;

/**
 * 用于获取客户Windows服务器的基本信息
 */
@Log4j
public class WindowsServerInfos extends AServerInfos {

    @Override
    protected String getCPUSerial() {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_Processor\") \n"
                + "For Each objItem in colItems \n" + "    Wscript.Echo objItem.ProcessorId \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";
        return execCommand("CPU", vbs);
    }

    @Override
    protected String getMainBoardSerial() {
        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_BaseBoard\") \n"
                + "For Each objItem in colItems \n" + "    Wscript.Echo objItem.SerialNumber \n"
                + "    exit for  ' do the first cpu only! \n" + "Next \n";
        return execCommand("MainBoardSerial", vbs);
    }

    private String execCommand(String fileName, String vbs){
        StringBuilder result= new StringBuilder();
        try {
            File file = File.createTempFile(fileName, ".vbs");
            file.deleteOnExit();
            try (FileWriter fw = new FileWriter(file)) {
                fw.write(vbs);
            }
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            try (
                BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                Stream<String> stringStream = br.lines()
            ) {
                stringStream.forEach(result::append);
            }
        } catch (Exception e) {
            log.error("获取"+ fileName +"信息错误", e);
        }
        return result.toString().trim();
    }

}
